package org.stvd.service.common.impl;

import java.util.Date;
import java.util.Map;

import javax.annotation.Resource;

import org.springframework.stereotype.Service;
import org.stvd.common.enums.UserLoginTypeEnum;
import org.stvd.common.enums.VerifyCodeTypeEnum;
import org.stvd.common.utils.MailUtil;
import org.stvd.common.utils.ServiceResult;
import org.stvd.common.utils.ServiceUtils;
import org.stvd.common.utils.VerifyUtil;
import org.stvd.core.util.DateUtil;
import org.stvd.core.util.StringUtil;
import org.stvd.entities.admin.UserLogin;
import org.stvd.entities.common.VerifyTmp;
import org.stvd.entities.common.VerifyTmpPK;
import org.stvd.repository.admin.UserLoginDao;
import org.stvd.repository.common.VerifyTmpDao;
import org.stvd.service.common.MailSendService;

@Service("mailSendService")
public class MailSendServiceImpl implements MailSendService {

    @Resource(name = "UserLoginDao")
    private UserLoginDao userLoginDao;
    
    @Resource(name = "VerifyTmpDao")
    private VerifyTmpDao verifyTmpDao;
    
    /**
     * 发送邮件
     * @param toMail 目标地址
     * @param subject 主题
     * @param content 内容
     * @return true-已发送(是否成功不能确定，只表示参数正确)；false-参数格式错误；
     */
    public boolean sendMail(String toMail, String subject, String content) {
        MailUtil mu = new MailUtil();
        mu.setToEmails(toMail);
        mu.setSubject(subject);
        mu.setContent(content);
        try {
            mu.sendEmail();
            return true;
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
    }

    @Override
    public ServiceResult<Map<String, Object>> sendAndBindingEmailCode(String systemName, String emailNumStr) {
        ServiceResult<Map<String, Object>> serviceResult = new ServiceResult<>();
        if(StringUtil.isEmpty(emailNumStr)) {
            serviceResult.setParamError("邮箱地址不能为空");
            return serviceResult;
        }
        if(!VerifyUtil.isEmail(emailNumStr)) {
            serviceResult.setParamError("邮箱格式有误");
            return serviceResult;
        }
        UserLogin userLogin = userLoginDao.findUserLoginByLoginAccount(emailNumStr);
        if(userLogin!=null) {
            serviceResult.setParamError("当前邮箱已绑定账号，请更换邮箱地址");
            return serviceResult;
        }
        VerifyTmp verifyTemp = verifyTmpDao
                .findByPK(new VerifyTmpPK(emailNumStr, VerifyCodeTypeEnum.Bind.getValue()));
        if (verifyTemp!=null && ((DateUtil.getSystemDate().getTime()
                - verifyTemp.getInputDatetime().getTime()) < (1000*60))) {
            serviceResult.setDataError("获取邮箱验证码过于频繁，请稍等片刻！");
            return serviceResult;
        }
        /* 发送验证邮件 */
        // 邮件主题
        String subject = systemName + "邮箱验证码邮件";
        String mailVcode = ServiceUtils.getRandomCode(6, "0"); //邮箱验证码
        StringBuffer contentTmp = new StringBuffer();
        contentTmp.append("<html><body>亲爱的 "+emailNumStr+"：<br />您好！"
                + "感谢您使用"+systemName+"！您的验证码为：<br/>");
        contentTmp.append("<br/><p style='font-size:36px;text-indent:2em'>"+mailVcode+"</p><br/>");
        contentTmp.append("您的验证码10分钟内有效，为了保证您的帐户安全，请勿向任何人提供此验证码！");
        contentTmp.append("<hr style='margin-left: initial;width: 100%; border:1px dashed #987cb9'>");
        contentTmp.append("<p style='color: #999;font-size: 14px;margin-top:10px;margin-bottom:40px'>本邮件由系统自动发送，请勿直接回复！</p>");
        contentTmp.append("</body></html>");
        if (this.sendMail(emailNumStr, subject, contentTmp.toString())) {
            Date nowTime = new Date();
            verifyTmpDao.update(new VerifyTmp(emailNumStr, VerifyCodeTypeEnum.Bind.getValue(), mailVcode, nowTime));
            serviceResult.setMessage("请登录您的邮箱『"+emailNumStr+"』查收验证码并完成绑定操作！");
        } else {
            serviceResult.setDataError("邮件发送失败，请重试！");
        }
        return serviceResult;
    }

    @Override
    public ServiceResult<Map<String, Object>> sendAndResetPasswordEmailCode(String systemName, String emailNumStr) {
        ServiceResult<Map<String, Object>> serviceResult = new ServiceResult<>();
        if(StringUtil.isEmpty(emailNumStr)) {
            serviceResult.setParamError("邮箱地址不能为空");
            return serviceResult;
        }
        if(!VerifyUtil.isEmail(emailNumStr)) {
            serviceResult.setParamError("邮箱格式有误");
            return serviceResult;
        }
        UserLogin userLogin = userLoginDao.findUserLoginByTypeAccount(UserLoginTypeEnum.Email.getValue(), emailNumStr);
        if(userLogin==null) {
            serviceResult.setParamError("当前邮箱尚未绑定，不能用于重置密码操作");
            return serviceResult;
        }
        VerifyTmp verifyTemp = verifyTmpDao
                .findByPK(new VerifyTmpPK(emailNumStr, VerifyCodeTypeEnum.Bind.getValue()));
        if (verifyTemp!=null && ((DateUtil.getSystemDate().getTime()
                - verifyTemp.getInputDatetime().getTime()) < (1000*60))) {
            serviceResult.setDataError("获取邮箱验证码过于频繁，请稍等片刻！");
            return serviceResult;
        }
        /* 发送验证邮件 */
        // 邮件主题
        String subject = systemName + "邮箱验证码邮件";
        String mailVcode = ServiceUtils.getRandomCode(6, "0"); //邮箱验证码
        StringBuffer contentTmp = new StringBuffer();
        contentTmp.append("<html><body>亲爱的 "+emailNumStr+"：<br />您好！"
                + "感谢您使用"+systemName+"！您的验证码为：<br/>");
        contentTmp.append("<br/><p style='font-size:36px;text-indent:2em'>"+mailVcode+"</p><br/>");
        contentTmp.append("您的验证码10分钟内有效，为了保证您的帐户安全，请勿向任何人提供此验证码！");
        contentTmp.append("<hr style='margin-left: initial;width: 100%; border:1px dashed #987cb9'>");
        contentTmp.append("<p style='color: #999;font-size: 14px;margin-top:10px;margin-bottom:40px'>本邮件由系统自动发送，请勿直接回复！</p>");
        contentTmp.append("</body></html>");
        if (this.sendMail(emailNumStr, subject, contentTmp.toString())) {
            Date nowTime = new Date();
            verifyTmpDao.update(new VerifyTmp(emailNumStr, VerifyCodeTypeEnum.ResetPassword.getValue(), mailVcode, nowTime));
            serviceResult.setMessage("请登录您的邮箱『"+emailNumStr+"』查收验证码并完成密码重置操作！");
        } else {
            serviceResult.setDataError("邮件发送失败，请重试！");
        }
        return serviceResult;
    }
}
